<template>
  <textarea id="re" ref="el" v-bind="$attrs" class="rich-editor" />
</template>

<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    width?: string;
    height?: string;
    modelValue: string;
  }>(),
  {
    width: "100%",
    height: "300px",
  }
);

let editor = $ref<any>(null);
const el = $ref<HTMLElement>();
onMounted(() => {
  !editor &&
    (editor = window.KindEditor.create("#re", {
      width: props.width,
      height: props.height,
      uploadJson: "/back/editor/upload",
      fileManagerJson: "/back/editor/fileManager",
      allowFileManager: true,
      afterBlur() {
        content = this.html();
      },
    }));
});

watch(
  () => props.modelValue,
  (val) => {
    if (val !== content) {
      content = val;
      editor?.html(val);
    }
  }
);

let content = $ref("");
const emit = defineEmits(["update:modelValue"]);
watchEffect(() => {
  emit("update:modelValue", content);
});
</script>

<style lang="less"></style>
